/*
 * The MIT License
 *
 * Copyright (C) 2010-2011 by Anthony Robinson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package jenkins.plugins.publish_over_ssh;

import hudson.EnvVars;
import hudson.FilePath;
import hudson.model.*;
import jenkins.plugins.publish_over.*;
import jenkins.plugins.publish_over_ssh.onepublish.UpdateUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("PMD.LooseCoupling") // serializable
public class BapSshAlwaysRunPublisherPlugin extends BapSshPublisherPlugin {

    private static final long serialVersionUID = 1L;

    public BapSshAlwaysRunPublisherPlugin(final ArrayList<BapSshPublisher> publishers, final boolean continueOnError,
                                          final boolean failOnError, final boolean alwaysPublishFromMaster, final String masterNodeName,
                                          final BapSshParamPublish paramPublish) {
        super(publishers, continueOnError, failOnError, alwaysPublishFromMaster, masterNodeName, paramPublish);
    }

    @Override
    protected boolean isBuildGoodEnoughToRun(final AbstractBuild<?, ?> build, final PrintStream console) {
        return true;
    }

    public boolean perform(final AbstractBuild<?, ?> build, final BuildListener listener) throws InterruptedException, IOException {
        //Map<String,List<UpdateUtil>> threads= new HashMap<>();
        ExecutorService threadPool= Executors.newCachedThreadPool();
        List<BapSshPublisher> publishs= this.getDelegate().getPublishers();
        for (BapSshPublisher publish:publishs){
            BPBuildEnv currentBuildEnv = new BPBuildEnv(this.getEnvironmentVariables(build, listener), build.getWorkspace(), build.getTimestamp());
            String consolePrefix="";
            BPBuildEnv targetBuildEnv = null;
            if("hudson.plugins.promoted_builds.Promotion".equals(build.getClass().getCanonicalName())) {
                AbstractBuild buildInfo;
                try {
                    Method result = build.getClass().getMethod("getTarget", (Class[])null);
                    buildInfo = (AbstractBuild)result.invoke(build, (Object[])null);
                } catch (Exception var9) {
                    throw new RuntimeException(jenkins.plugins.publish_over.Messages.exception_failedToGetPromotedBuild(), var9);
                }

                targetBuildEnv = new BPBuildEnv(this.getEnvironmentVariables(buildInfo, listener), new FilePath(buildInfo.getArtifactsDir()), buildInfo.getTimestamp());
            }
            BPBuildInfo buildInfo1 = new BPBuildInfo(listener, consolePrefix, Hudson.getInstance().getRootPath(), currentBuildEnv, targetBuildEnv);
            BPHostConfiguration e = this.getConfiguration(publish.getConfigName());
            List<BapSshTransfer> transfs= publish.getTransfers();
            for(BapSshTransfer transf:transfs){
                BapSshClient client=(BapSshClient)e.createClient(buildInfo1);
                UpdateUtil update= new UpdateUtil();
                update.setClient(client);
                update.setListener(listener);
                update.setTransf(transf);
                update.setServerName(publish.getConfigName());
                threadPool.execute(update);
            }
        }
        threadPool.shutdown();
        boolean flag=false;
        while (!flag){
            Thread.sleep(1000);
            flag=threadPool.isTerminated();
        }
        return true;
//        Result result1 = this.getInstanceConfig().getConfiguration()
      //return perform(build, null, listener);
        //return true;
    }

    private TreeMap<String, String> getEnvironmentVariables(AbstractBuild<?, ?> build, TaskListener listener) {
        try {
            EnvVars e = build.getEnvironment(listener);
            e.putAll(build.getBuildVariables());
            return e;
        } catch (Exception var4) {
            throw new RuntimeException(jenkins.plugins.publish_over.Messages.exception_failedToGetEnvVars(), var4);
        }
    }


    public boolean equals(final Object that) {
        if (this == that) return true;
        if (that == null || getClass() != that.getClass()) return false;

        return addToEquals(new EqualsBuilder(), (BapSshAlwaysRunPublisherPlugin) that).isEquals();
    }

    public int hashCode() {
        return addToHashCode(new HashCodeBuilder()).toHashCode();
    }

    public String toString() {
        return addToToString(new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)).toString();
    }

}
